package org.socket.api.rest;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.socket.api.repo.ServerConfigRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@RestController
@RequestMapping("/server/config")
public class ServerConfig {
	
	@Autowired
	private ServerConfigRepo serverConfigRepo;
	
	private static Logger log = LoggerFactory.getLogger(ServerConfig.class);

	@GetMapping("/save")
	public String ss(org.socket.api.entity.ServerConfig config) {
		log.debug(JSON.toJSONString(config));
		if(config.getIp() == null || config.getSecurity() == null || config.getSname() == null) {
			return "error";
		}
		List<org.socket.api.entity.ServerConfig> list = serverConfigRepo.findByParam(config.getIp(), config.getPort(), config.getSecurity(), config.getSname());
		if(list == null || list.isEmpty()) {
			serverConfigRepo.save(config);
		}
		return "success";
	}
	
	@GetMapping("/list")
	public List<String> ss() {
		List<String> res = new ArrayList<String>();
		res.add("其他");
		Iterable<org.socket.api.entity.ServerConfig> list = serverConfigRepo.findAll();
		Iterator<org.socket.api.entity.ServerConfig> iterator = list.iterator();
		while(iterator.hasNext()) {
			org.socket.api.entity.ServerConfig config = iterator.next();
			if(!res.contains(config.getSname())) {
				res.add(config.getSname());
			}
		}
		log.debug(JSON.toJSONString(res));
		return res;
	}
	
	@GetMapping("/details")
	public List<JSONObject> ss(String sname) {
		List<JSONObject> res = new ArrayList<JSONObject>();
		Sort sort = Sort.by("id");
		PageRequest page = PageRequest.of(0, 10, sort);
		List<org.socket.api.entity.ServerConfig> list = serverConfigRepo.findBySname(sname, page);
		for(org.socket.api.entity.ServerConfig sc : list) {
			res.add(JSON.parseObject(JSON.toJSONString(sc)));
		}
		log.debug(JSON.toJSONString(res));
		return res;
	}
}
